import AddressParse from 'address-parse';
import { useEffect, useState } from 'react';
import Slider from 'react-slick';
import { apiCardDetailConvertOrderPay, apiGetServerLink, apiGetSmsCodeNewEncrypt, apiOssUpload } from '../api';
import AppBar from '../components/appBar';
import Loading from '../components/loading';
import AreaPicker from '../components/area_picker';
import MReceiptPicker from '../components/m_receipt_picker/m_receipt_picker';
import Page from '../components/page';
import ProtocolDialog from '../components/protocolDialog';
import MCheckbox from '../components/radioBox';
import ViewPictureDialog from '../components/viewPictureDialog';
import main from '../main';
import { DetailJson, excludedOptions } from '../types';
import showPayPage, { PayType } from '../utils/pay';
import { copyToClipboard, isWeixinEnv, showToast, maskText } from '../utils/utils';
import dataList from '../utils/data.json';
import RefreshDialog from '../components/refreshDialog';
import regions from '../components/m_receipt_picker/area.json';
import WrongDialog from '../components/wrongDialog';
import NotWxPageDialog from '../components/notWxPageDialog';
import CountdownTimer from '../components/countdown_timer';

interface Props {
  detailData: DetailJson;
  paramOrderId: string;
  onUpdate: () => void;
}
let isWx = isWeixinEnv();
let excludedList: excludedOptions;
let kfFlag = false;
export default function HomePage({ detailData, paramOrderId, onUpdate }: Props) {
  const [isExpired, setIsExpired] = useState(false);
  const [idName, setidName] = useState<string>(detailData?.idName ?? '');
  const [receiverName, setreceiverName] = useState<string>(detailData?.receiverName ?? '');
  const [idNumber, setidNumber] = useState<string>(detailData?.idNumber ?? '');
  const [idNumblurState, setIdNumBlurState] = useState<boolean>(detailData.idNumber ? true : false);
  const [receiverPhone, setreceiverPhone] = useState<string>(detailData?.receiverPhone ?? '');
  const [provinceName, setprovinceName] = useState<string>(detailData?.provinceName ?? '');
  const [cityName, setcityName] = useState<string>(detailData?.cityName ?? '');
  const [countyName, setcountyName] = useState<string>(detailData?.countyName ?? '');
  const [phoneCode, setphoneCode] = useState<string>('');
  const [countdown, setCountdown] = useState<number>(0);
  const [receiverAddress, setreceiverAddress] = useState<string>(detailData?.receiverAddress ?? '');
  // 智能识别
  const [message, setmessage] = useState('');
  // 身份证头像照片
  const [cardAvatar, setCardAvatar] = useState<string | undefined>(detailData?.idReverseUrl ?? '');
  // 身份证国徽照片
  const [cardNationalEmblem, setNationalEmblem] = useState<string | undefined>(detailData?.idFrontUrl ?? '');
  // 免冠正面照片
  const [handPhoto, setHandPhoto] = useState<string | undefined>(detailData?.faceUrl ?? '');
  // 自定义照片
  const [definedPhotoImg, setdefinedPhotoImg] = useState<string | undefined>(detailData?.definedPhotoImg ?? '');
  // 查看图片
  const [viewPictureDialogShow, setviewPictureDialogShow] = useState<string | undefined>();
  // 上传照片显示loading
  const [uploadLoading, setuploadLoading] = useState<boolean>(false);
  // 已选同意协议
  const [checkProtocol, setCheckProtocl] = useState(false);
  // 显示协议弹窗
  const [showProtocol, setShowProtocol] = useState<string>();
  // 错误信息弹窗
  const [wrongDialog, setwrongDialog] = useState<string | undefined>();
  // 支付类型
  const [payType, setpayType] = useState<string>(isWx ? PayType.WECHATJSPAY : PayType.ALIPAGE);
  // 支付金额发生变化-刷新页面弹窗
  const [refreshDialogShow, setRefreshDialogShow] = useState<boolean>(false);
  // 订单记录-轮播图参数
  const setting = {
    speed: 500,
    dots: false,
    infinite: true,
    autoplay: true,
    vertical: true,
    autoplaySpeed: 2000,
    slidesToShow: 1,
    slidesToScroll: 1,
    prevArrow: <SampleNextArrow />,
    nextArrow: <SamplePrevArrow />,
  };
  function SampleNextArrow() {
    return <div className="w-10 h-10" />;
  }
  function SamplePrevArrow() {
    return <div className="w-10 h-10" />;
  }
  useEffect(() => {
    if (detailData) {
      setidName(detailData?.idName ?? '');
      setreceiverName(detailData?.receiverName ?? '');
      setidNumber(detailData?.idNumber ?? '');
      setreceiverPhone(detailData?.receiverPhone ?? '');
      setprovinceName(detailData?.provinceName ?? '');
      setcityName(detailData?.cityName ?? '');
      setcountyName(detailData?.countyName ?? '');
      setreceiverAddress(detailData?.receiverAddress ?? '');
      setCardAvatar(detailData?.idReverseUrl ?? '');
      setNationalEmblem(detailData?.idFrontUrl ?? '');
      setHandPhoto(detailData?.faceUrl ?? '');
    }
  }, [detailData]);
  // 上传照片
  const chooseImg = async (t: FileList | null, type: string) => {
    if (t && t[0]) {
      if (t[0].size / 1024 / 1024 > 10) return showToast('照片不可以上传超过10MB');
      setuploadLoading(true);
      try {
        const res = await apiOssUpload(t[0]);
        if (res) {
          if (type === 'cardAvatar') {
            setCardAvatar(res);
          } else if (type === 'cardNationalEmblem') {
            setNationalEmblem(res);
          } else if (type === 'handPhoto') {
            setHandPhoto(res);
          } else if (type === 'definedPhotoImg') {
            setdefinedPhotoImg(res);
          }
        }
      } catch (error) {
      } finally {
        setuploadLoading(false);
      }
    }
  };
  // 智能识别
  const parseAddress = () => {
    if (!!message) {
      const result = AddressParse.parse(message);
      let _list = result[0];
      let pExist = excludedList?.provinces.includes(_list?.province ?? '');
      let cExist = excludedList?.cities.includes(_list?.city ?? '');
      let aExist = excludedList?.district.includes(_list?.area ?? '');
      if (!pExist) {
        setprovinceName(_list?.province ?? '');
        if (!cExist) {
          setcityName(_list?.city ?? '');
          if (!aExist) {
            setcountyName(_list?.area ?? '');
          } else {
            setcountyName('');
            showToast('该区/县暂不支持发货');
          }
        } else {
          setcityName('');
          setcountyName('');
          showToast('该市暂不支持发货');
        }
      } else {
        setprovinceName('');
        setcityName('');
        setcountyName('');
        showToast('该省份暂不支持发货');
      }
      setreceiverName(_list?.name ?? '');
      setreceiverPhone(_list?.mobile ?? '');
      setreceiverAddress(_list?.details ?? '');
      if (detailData?.convertType === 1) {
        setidName(_list?.name ?? '');
      }
    } else {
      showToast('请输入要识别的信息');
    }
  };
  // 选择地区
  function handleCityPickerChange(v: string[]) {
    if (v[0] === '暂无可选城市') return;
    setprovinceName(!!v[0] ? v[0] : '');
    setcityName(!!v[1] ? v[1] : '');
    setcountyName(!!v[2] ? v[2] : '');
  }

  // 提交
  async function handleSubmit() {
    console.log('idName', idName);
    let msg = '';
    let phoneReg = /^1[3-9]{1}[0-9]{9}$/;
    let idRegex = /(^\d{15}$)|(^\d{17}(\d|X|x)$)/;
    if (!receiverName) {
      msg = '请输入收件人姓名';
    } else if (!detailData?.receiverAddress && !phoneCode) {
      msg = '请输入验证码';
    } else if (!receiverPhone) {
      msg = '请输入收货电话';
    } else if (!phoneReg.test(receiverPhone)) {
      msg = '请输入正确的手机号';
    } else if (!provinceName) {
      msg = '请选择省份';
    } else if (!cityName) {
      msg = '请选择市';
    } else if (!countyName) {
      msg = '请选择区';
    } else if (!receiverAddress) {
      msg = '请输入详细地址';
    } else if (!detailData?.receiverAddress && !checkProtocol) {
      msg = '请阅读并同意协议';
    } else if (detailData?.convertType === 1 && !idName) {
      msg = '请输入身份证姓名';
    } else if (detailData?.convertType === 1 && !idNumber) {
      msg = '请输入身份证号码';
    } else if (detailData?.convertType === 1 && !idRegex.test(idNumber)) {
      msg = '请输入正确格式身份证号码';
    } else if (detailData?.needIdCard === 1 && !cardAvatar) {
      msg = '请上传身份证头像照片';
    } else if (detailData?.needIdCard === 1 && !cardNationalEmblem) {
      msg = '请上传身份证国徽照片';
    } else if (detailData?.needIdCard === 1 && !handPhoto) {
      msg = '请上传免冠正面照片';
    } else if (detailData?.isDefinedPhoto === 'Y' && !definedPhotoImg) {
      msg = '请上传照片';
    }
    if (msg !== '') {
      showToast(msg);
      return;
    }
    setuploadLoading(true);
    let uri = window.location.href;
    let redirect_uri = encodeURIComponent(uri);
    try {
      let res = await apiCardDetailConvertOrderPay(
        Object.assign(
          {},
          {
            orderId: detailData?.id,
            openId: main.openId,
            appName: main.appName,
            url: redirect_uri,
            payAmount: detailData?.payAmount,
          },
          {
            payType: 0,
            receiverName,
            receiverPhone,
            provinceName,
            cityName,
            countyName,
            receiverAddress,
            idName,
            idNumber,
            idFrontUrl: cardNationalEmblem,
            idReverseUrl: cardAvatar,
            faceUrl: handPhoto,
            phoneCode,
            definedPhotoImg,
          }
        )
      );
      let data = res.data;
      if (data.code === 200) {
        showToast('提交成功');
        if (data.data.isPay) {
          let payRes = await showPayPage(data.data.result, payType);
          if (payRes.code === 200) {
            console.log('微信支付成功');
            onUpdate();
          } else if (payRes.code === 300) {
            console.log('payRes', payRes);
            window.location.href = payRes.url;
          }
        } else {
          onUpdate();
        }
      } else if (data.code === 1101) {
        // 支付金额发生变化
        setRefreshDialogShow(true);
      } else {
        setwrongDialog(data.msg ?? '提交失败');
        // showToast(data.msg ?? '提交失败');
      }
    } catch (e: any) {
      showToast(e.message ?? '提交失败');
    } finally {
      setuploadLoading(false);
    }
  }
  function handleCopyHost() {
    let url = window.location.href;
    copyToClipboard(url);
  }
  // 查看客服链接
  async function toView() {
    if (kfFlag) return;
    kfFlag = true;
    try {
      let res = await apiGetServerLink({ orderId: paramOrderId });
      let data = res.data;
      if (data.code === 200 && !!data.msg) {
        window.location.href = data.msg;
      } else {
        showToast('网络繁忙，请稍后再试');
      }
    } catch (e: any) {
      showToast('网络繁忙，请稍后再试');
    } finally {
      setuploadLoading(false);
      kfFlag = false;
    }
  }
  async function saveCode() {
    let msg = '';
    let phoneReg = /^1[3-9]{1}[0-9]{9}$/;
    if (!receiverPhone) {
      msg = '请输入收货电话';
    } else if (!phoneReg.test(receiverPhone)) {
      msg = '请输入正确的手机号';
    }
    if (msg) {
      return showToast(msg);
    }
    setuploadLoading(true);
    try {
      let res = await apiGetSmsCodeNewEncrypt({
        phone: receiverPhone,
        type: detailData?.convertType || '',
        iccid: detailData?.iccid || '',
        smsType: 'convert',
      });
      let data = res.data;
      if (data.code === 200) {
        showToast('发送成功');
        setCountdown(60); // 设置初始倒计时时间
        const timer = setInterval(() => {
          setCountdown((prev) => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        showToast('发送失败');
      }
    } catch (e: any) {
      showToast('发送失败');
    } finally {
      setuploadLoading(false);
    }
  }
  let phoneType = detailData?.convertType === 1;
  excludedList = {
    provinces: phoneType ? (detailData?.stopProvince ?? '')!.split(',') : ['云南省', '新疆维吾尔自治区', '西藏自治区'],
    cities: phoneType ? (detailData?.stopCity ?? '')!.split(',') : ['茂名市'],
    district: phoneType ? (detailData?.stopCounty ?? '')!.split(',') : [],
  };
  const wxPage = (
    <div style={{ width: '100%', height: '100%' }}>
      <div className="pt-10 pl-10 pr-10 font-size-12">
        {detailData?.goodsHeadImg && <img src={detailData?.goodsHeadImg} className="bw-100" alt="" />}
        {detailData?.convertType !== 1 && (
          <>
            <div className="font-widget-600 w-100 text-color-3 mb-5 tips-header font-size-14">产品信息</div>
            <div className="bg-white border-radius-8 p-10">
              <div className="d-flex-r mb-10">
                <span className="w-80 text-right">推荐产品：</span>
                <div className="flex-1 d-flex-r flex-wrap text-color-6 pl-15">
                  {detailData?.businessJson?.cardProductName ?? '--'}
                </div>
              </div>
              <div className="d-flex-r mb-10">
                <span className="w-80 text-right">售价：</span>
                <div className="flex-1 d-flex-r flex-wrap text-color-6 pl-15">
                  {detailData?.businessJson?.cardProductPrice ?? '--'}（元）
                </div>
              </div>
              <div className="d-flex-r mb-10">
                <span className="w-80 text-right">老卡余额：</span>
                <div className="flex-1 d-flex-r flex-wrap text-color-6 pl-15">{detailData?.balance ?? '--'}（元）</div>
              </div>
              <div className="d-flex-r mb-10">
                <span className="w-80 text-right">补差价：</span>
                <div className="flex-1 d-flex-r flex-wrap text-color-6 pl-15">
                  {detailData?.payAmount ?? '--'}（元）
                </div>
              </div>
            </div>
          </>
        )}
      </div>
      <div className="pb-10 pl-10 pr-10">
        <div className="countdown-goods">
          {/* 订单记录-轮播图 */}
          <Slider className="order-slider" {...setting}>
            {dataList.map((_, index) => (
              <RandomNum key={index} />
            ))}
          </Slider>
        </div>
        <div className="bg-p pt-20 pb-20 border-radius-4 mb-10">
          {detailData.createTime && (
            <CountdownTimer onchange={(v) => setIsExpired(v)} createTime={detailData.createTime} />
          )}
        </div>
        <div className="font-widget-600 text-color-purered bg-white p-5 text-center border-radius-4 pt-10 pb-10">
          温馨提示:为了物流可以正常派送，请您填写详细的收货地址及正确的联系方式，感谢您的配合!
        </div>
        <div className="pt-10">
          <div className="prop-line mb-10 d-flex-r ai-center">
            <div className="label">收件人姓名：</div>
            <div className="value flex-1">
              <input
                className="input"
                placeholder={detailData?.convertType === 1 ? '与身份证上的姓名一致(已加密)' : '请输入收件人姓名'}
                value={receiverName}
                onChange={(e) => {
                  setreceiverName(e.target.value);
                  if (detailData?.convertType === 1) {
                    setidName(e.target.value);
                  }
                }}
              />
            </div>
          </div>
          {detailData?.convertType === 1 && (
            <>
              {/* <div className="prop-line mb-10 d-flex-r ai-center">
                <div className="label">身份证姓名：</div>
                <div className="value flex-1">
                  <input
                    className="input"
                    placeholder="请输入身份证姓名"
                    value={idName}
                    onChange={(e) => setidName(e.target.value)}
                  />
                </div>
              </div> */}
              <div className="prop-line mb-10 d-flex-r ai-center">
                <div className="label">身份证号码：</div>
                <div className="value flex-1">
                  <input
                    className="input"
                    placeholder="请输入身份证号码"
                    value={
                      idNumblurState && idNumber ? idNumber.replaceAll(/^(.{6}).*?(.{4})$/g, '$1*****$2') : idNumber
                    }
                    onChange={(e) => setidNumber(e.target.value)}
                    onBlur={() => setIdNumBlurState(true)}
                    onFocus={() => setIdNumBlurState(false)}
                  />
                </div>
              </div>
            </>
          )}
          <div className="prop-line mb-10 d-flex-r ai-center">
            <div className="label">收货电话：</div>
            <div className="value flex-1">
              <input
                className="input"
                placeholder="请输入收件手机号"
                value={receiverPhone}
                onChange={(e) => setreceiverPhone(e.target.value)}
              />
            </div>
          </div>
          <div className="prop-line mb-10 d-flex-r ai-center">
            <div className="label">验证码：</div>
            <div className="value flex-1 d-flex-r jc-between ai-center">
              <input
                className="input"
                placeholder="请输入验证码"
                value={phoneCode}
                style={{ width: 'calc(100% - 150px)' }}
                onChange={(e) => setphoneCode(e.target.value)}
              />

              <span
                className="w-70 border-radius-4 bg-p text-color-white font-size-12 h-25 d-flex-r ai-center jc-center"
                onClick={countdown === 0 ? saveCode : undefined}
              >
                {countdown > 0 ? `${countdown}s 后重发` : '获取验证码'}
              </span>
            </div>
          </div>
          <div className="prop-line mb-10 d-flex-r ai-center">
            <div className="label">收货地址：</div>
            <div className="value flex-1">
              <AreaPicker
                excludedList={excludedList}
                provinceName={provinceName}
                cityName={cityName}
                countyName={countyName}
                onChange={(v) => handleCityPickerChange(v)}
              />
            </div>
          </div>
          <div className="prop-line mb-10 d-flex-r ai-center">
            <div className="label">详细地址：</div>
            <div className="value flex-1">
              <input
                className="input"
                placeholder="请输入详细地址"
                value={receiverAddress}
                onChange={(e) => setreceiverAddress(e.target.value)}
              />
            </div>
          </div>
        </div>
        {/*  <div className="mt-15 mb-10 bg-white border-radius-8 p-10 border d-flex-r">
          <textarea
            className="recognition-ipt flex-1 p-0"
            placeholder="姓名+手机号码+xx省+xx市+xx区或xx镇+xx大街+xxx二号楼xx室"
            value={message}
            onChange={(e) => setmessage(e.target.value)}
          />
          <div
            className="recognition-title ml-10 pl-10 d-flex-r ai-center jc-center border-left"
            onClick={parseAddress}
          >
            识别地址
          </div>
        </div> */}
      </div>

      <div className="pl-10 pr-10">
        {detailData?.needIdCard === 1 && (
          <>
            <div className="font-size-14 font-widget-600">
              根据有关部门要求，必须上传真实身份证照片。<span className="text-color-red">未上传照片，订单无效</span>
            </div>
            <div className="mt-10">
              <div className="prop-line d-flex-r ai-center">
                <div className="flex-1 pic pb-5 d-flex-r">
                  {cardAvatar ? (
                    <div className="upload-pic border-radius-4 overflow-hidden mr-5">
                      <img
                        className="bw-100 bh-100"
                        src={cardAvatar}
                        alt=""
                        onClick={() => setviewPictureDialogShow(cardAvatar)}
                      />
                      <div className="icon-close-block" onClick={() => setCardAvatar(undefined)}>
                        <img className="bw-100 bh-100" src="./pic/icon_close.png" alt="" />
                      </div>
                    </div>
                  ) : (
                    <div className={`upload-pic border border-radius-4 text-center d-flex-r ai-center jc-center`}>
                      <img className="icon-12" src="./pic/icon_plus.png" alt="" />
                      <input
                        className="upload-input bw-100 bh-100"
                        type="file"
                        accept=".jpg,.png,.jpeg"
                        onChange={(e) => {
                          chooseImg(e.target.files, 'cardAvatar');
                        }}
                      />
                    </div>
                  )}
                  <div className="example-block">
                    <img
                      onClick={() => setviewPictureDialogShow('./pic/iccid1.jpg')}
                      className="example-img"
                      src="./pic/iccid1.jpg"
                      alt=""
                    />
                  </div>
                </div>
              </div>
              <span className="text-color-6 font-size-12">
                手机横拍，保证边角完整信息清晰，不能反光、翻拍、模糊、边角残缺等。
              </span>
            </div>
            <div className="mt-10">
              <div className="prop-line d-flex-r ai-center">
                <div className="flex-1 pic pb-5 d-flex-r">
                  {cardNationalEmblem ? (
                    <div className="upload-pic border-radius-4 overflow-hidden mr-5">
                      <img
                        className="bw-100 bh-100"
                        src={cardNationalEmblem}
                        alt=""
                        onClick={() => setviewPictureDialogShow(cardNationalEmblem)}
                      />
                      <div className="icon-close-block" onClick={() => setNationalEmblem(undefined)}>
                        <img className="bw-100 bh-100" src="./pic/icon_close.png" alt="" />
                      </div>
                    </div>
                  ) : (
                    <div className={`upload-pic border border-radius-4 text-center d-flex-r ai-center jc-center`}>
                      <img className="icon-12" src="./pic/icon_plus.png" alt="" />
                      <input
                        className="upload-input bw-100 bh-100"
                        type="file"
                        accept=".jpg,.png,.jpeg"
                        onChange={(e) => {
                          chooseImg(e.target.files, 'cardNationalEmblem');
                        }}
                      />
                    </div>
                  )}
                  <div className="example-block">
                    <img
                      className="example-img"
                      onClick={() => setviewPictureDialogShow('./pic/iccid2.jpg')}
                      src="./pic/iccid2.jpg"
                      alt=""
                    />
                  </div>
                </div>
              </div>
              <span className="text-color-6 font-size-12">
                手机横拍，保证边角完整信息清晰，不能反光、翻拍、模糊、边角残缺等。
              </span>
            </div>
            <div className="mt-10">
              <div className="prop-line d-flex-r ai-center">
                <div className="flex-1 pic pb-5 d-flex-r">
                  {handPhoto ? (
                    <div className="upload-pic border-radius-4 overflow-hidden mr-5">
                      <img
                        className="bw-100 bh-100"
                        src={handPhoto}
                        alt=""
                        onClick={() => setviewPictureDialogShow(handPhoto)}
                      />
                      <div className="icon-close-block" onClick={() => setHandPhoto(undefined)}>
                        <img className="bw-100 bh-100" src="./pic/icon_close.png" alt="" />
                      </div>
                    </div>
                  ) : (
                    <div className={`upload-pic border border-radius-4 text-center d-flex-r ai-center jc-center`}>
                      <img className="icon-12" src="./pic/icon_plus.png" alt="" />
                      <input
                        className="upload-input bw-100 bh-100"
                        type="file"
                        accept=".jpg,.png,.jpeg"
                        onChange={(e) => {
                          chooseImg(e.target.files, 'handPhoto');
                        }}
                      />
                    </div>
                  )}
                  <div className="example-block">
                    <img
                      className="example-img"
                      onClick={() => setviewPictureDialogShow('./pic/iccid3.jpg')}
                      src="./pic/iccid3.jpg"
                      alt=""
                    />
                  </div>
                </div>
              </div>
              <span className="text-color-6 font-size-12">
                请拍摄本人真实环境清晰正面免冠人像，不能反光，有水印，PS、上传证件照等。
              </span>
            </div>
          </>
        )}
        {detailData?.isDefinedPhoto === 'Y' && (
          <>
            <div className="mt-10">
              <div className="prop-line d-flex-r ai-center">
                <div className="flex-1 pic pb-5 d-flex-r">
                  {definedPhotoImg ? (
                    <div className="upload-pic border-radius-4 overflow-hidden mr-5">
                      <img
                        className="bw-100 bh-100"
                        src={definedPhotoImg}
                        alt=""
                        onClick={() => setviewPictureDialogShow(definedPhotoImg)}
                      />
                      <div className="icon-close-block" onClick={() => setdefinedPhotoImg(undefined)}>
                        <img className="bw-100 bh-100" src="./pic/icon_close.png" alt="" />
                      </div>
                    </div>
                  ) : (
                    <div className={`upload-pic border border-radius-4 text-center d-flex-r ai-center jc-center`}>
                      <img className="icon-12" src="./pic/icon_plus.png" alt="" />
                      <input
                        className="upload-input bw-100 bh-100"
                        type="file"
                        accept=".jpg,.png,.jpeg"
                        onChange={(e) => {
                          chooseImg(e.target.files, 'definedPhotoImg');
                        }}
                      />
                    </div>
                  )}
                  <div className="example-block">
                    <img
                      onClick={() => setviewPictureDialogShow('./pic/iccid4.png')}
                      className="example-img"
                      src="./pic/iccid4.png"
                      alt=""
                    />
                  </div>
                </div>
              </div>
              <span className="text-color-6 font-size-12">{detailData?.definedPhotoDesc}</span>
              <div className="mt-5 mb-20 text-color-orange border-radius-10 bg-white p-10 pb-15 box-shadow pos-r">
                <div
                  onClick={() => {
                    window.location.href = 'https://getsimnum.caict.ac.cn/m/#/';
                  }}
                  className="d-flex-r ai-center jc-center"
                >
                  <img className="w-35 h-30" src="./pic/icon_searchidno.png" alt="" />
                  <span className="font-size-16 ml-10 font-widget-700 text-color-p">一证通查询</span>
                </div>
                <span className="text-color-9 font-size-12 pos-a r-10 b-5">名下电话卡数</span>
              </div>
            </div>
          </>
        )}
        <div className="d-flex-r pb-10">
          <MCheckbox value={checkProtocol} onChange={(v) => setCheckProtocl(v)} />
          <div className="ml-10 font-size-12">
            <span onClick={() => setCheckProtocl(!checkProtocol)}>我已阅读并同意</span>
            <span className="text-color-p" onClick={() => setShowProtocol('userInfo')}>
              《关于客户个人信息收集、使用规则的公告》
            </span>
            <span className="text-color-p" onClick={() => setShowProtocol('phone')}>
              《办理电话号码开户法律风险及防范提示告知书》
            </span>
            <span className="text-color-p" onClick={() => setShowProtocol('noticeYD')}>
              《关于客户个人信息收集、使用及保护的公告》
            </span>
          </div>
        </div>
        {Number(detailData?.payAmount ?? 0) > 0 && (
          <>
            <div className="font-widget-600 w-100 text-color-3 mb-5 tips-header">支付方式</div>
            <div className="form-block mb-20 mt-10 border-radius-10 bg-white p-10 box-shadow">
              <div className="d-flex-r ai-center mt-14">
                <img src="./pic/icon_pay_wx.png" className="icon-20 mr-10" alt="" />
                <div className="flex-1">微信</div>
                <MCheckbox value={PayType.WECHATJSPAY === payType} onChange={() => setpayType(PayType.WECHATJSPAY)} />
              </div>

              {/* <div className="d-flex-r ai-center mt-14">
                   <img src="./pic/icon_pay_aili.png" className="icon-20 mr-10" alt="" />
                   <div className="flex-1">支付宝</div>
                   <MCheckbox value={PayType.ALIPAGE === payType} onChange={() => setpayType(PayType.ALIPAGE)} />
                 </div> */}

              {/* {!isWx && (
                <div className="mt-20 d-flex-r ai-center">
                  <span className="font-size-12 text-color-6 flex-1">如需微信支付，请复制链接到微信打开！</span>
                  <div
                    className="bg-p w-80 border-radius-4 text-color-white pt-5 pb-5 text-center"
                    onClick={handleCopyHost}
                  >
                    复&nbsp;制
                  </div>
                </div>
              )} */}
            </div>
          </>
        )}
        <div className="font-widget-600 text-color-0 bg-white p-10 text-center border-radius-8 pl-10 pr-10">
          因运营商规定，<span className="text-color-purered">如未满18周岁</span>不能激活请勿下单，感谢您的理解!
        </div>

        {detailData?.goodsDetail && (
          <div className="goods-detail" dangerouslySetInnerHTML={{ __html: detailData?.goodsDetail }} />
        )}
        <div className="w-10 h-70" />
      </div>
      <div className="p-10 footer-btn">
        <div className="submit-btn" onClick={handleSubmit}>
          {Number(detailData?.payAmount ?? 0) > 0 ? `立即支付¥${detailData?.payAmount}` : '立即办理（包邮）'}
        </div>
      </div>
      {uploadLoading && (
        <Loading
          tips={'正在加载中...'}
          loadingClass="bh-100 overflow-hidden text-color-white d-flex-r ai-center jc-center mt-0 bg-shallow"
        />
      )}
      {/* 查看图片 */}
      {viewPictureDialogShow && (
        <ViewPictureDialog imgPath={viewPictureDialogShow} onClose={() => setviewPictureDialogShow(undefined)} />
      )}
      {/* 价格发生变化刷新页面弹窗 */}
      {refreshDialogShow && (
        <RefreshDialog
          onClose={(v) => {
            setRefreshDialogShow(false);
            if (v) onUpdate();
          }}
        />
      )}
      {/* 协议弹窗 */}
      {showProtocol && <ProtocolDialog type={showProtocol} onClose={() => setShowProtocol(undefined)} />}
      {/* 错误弹窗 */}
      {wrongDialog && (
        <WrongDialog
          title="提单失败"
          text={wrongDialog}
          confirmText="修改申请信息"
          onClose={() => setwrongDialog(undefined)}
        />
      )}
    </div>
  );
  const notWxPage = (
    <div style={{ width: '100%', height: '100%', background: '#fff' }}>
      {/* <div className="home-page-content d-flex-c">
      <img className="home-page-img" src={'./pic/info-fill.png'} />
      <div className="home-page-text">
        请在微信客户端打开链接
      </div>
    </div> */}
      <NotWxPageDialog title="温馨提示" confirmText="复制链接" onClose={() => setwrongDialog(undefined)} />
    </div>
  );

  if (isExpired || detailData?.orderStatus === 99) {
    return (
      <div className="home-page bw-100 bvh-100 d-flex-c ai-center">
        <div className="d-flex-c jc-center ai-center mt-100 bw-100 pb-10">
          <img className="w-50" src="./pic/icon_wait.png" alt="" />
          <span className="m-20 font-widget-600 font-size-20 text-center">该链接已过期，请联系客服重新获取！</span>
        </div>
        <div className="submit-btn font-size-14" onClick={toView}>
          联系客服
        </div>
      </div>
    );
  }
  // 待支付-并且填写过信息
  if (detailData?.orderStatus === 1 && !!detailData?.receiverAddress) {
    let address =
      (detailData?.provinceName ?? '') +
      (detailData?.cityName ?? '') +
      (detailData?.countyName ?? '') +
      (detailData?.receiverAddress ?? '');
    return (
      <div className="bw-100 bvh-100 d-flex-c ai-center">
        <div className="d-flex-r jc-center ai-center mt-60 border-bottom bw-100 pb-20">
          <img className="w-50" src="./pic/icon_wait.png" alt="" />
          <span className="ml-20 font-widget-600 font-size-20">待支付</span>
        </div>
        <div className="bw-100 mt-30">
          <div className="d-flex-r p-10 pl-20">
            <div className="w-80 font-widget-600 font-size-14">充值卡号</div>
            {detailData?.iccid ? maskText(detailData?.iccid) : ''}
          </div>
          <div className="d-flex-r p-10 pl-20">
            <div className="w-80 font-widget-600 font-size-14">支付金额</div>
            {parseFloat(detailData?.payAmount ?? '0').toFixed(2)}
          </div>
          <div className="d-flex-r p-10 pl-20">
            <div className="w-80 font-widget-600 font-size-14">下单地址</div>
            <div className="flex-1">
              {maskText(address, /(.{12}).*/g, address.length > 12 ? '$1' + '*'.repeat(address.length - 12) : '')}
            </div>
          </div>
          <div className="d-flex-r p-10 pl-20">
            <div className="w-80 font-widget-600 font-size-14">状态</div>
            待支付
          </div>
          <div className="mt-20 d-flex-r ai-center jc-center">
            <div className="bg-p text-color-white pl-30 pr-30 pt-10 pb-10 border-radius-4" onClick={handleSubmit}>
              立即支付
            </div>
          </div>
        </div>
      </div>
    );
  }
  return (
    <Page
      className="home-page d-flex-c"
      contentClassName="flex-1 overflow-y"
      appBar={
        detailData?.convertType === 1 ? false : <AppBar showBack={false} className="text-color-0" title="换卡申请" />
      }
    >
      {Number(detailData?.payAmount ?? 0) === 0 || isWx ? wxPage : notWxPage}
    </Page>
  );
}

function RandomNum() {
  // 生成随机手机号
  const [phone, setPhone] = useState<string>();
  // 生成订单时间随机数
  const [randomNum, setRandomNum] = useState(0);
  let phoneNumber = '';
  useEffect(() => {
    let num = Math.floor(Math.random() * 8) + 1;
    setRandomNum(num);
    phoneNumber += 1;
    for (let i = 0; i < 10; i++) {
      phoneNumber += Math.floor(Math.random() * 6) + 3; // 生成随机数字并添加到手机号码中
    }
    var phoneNumber1 = phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    setPhone(phoneNumber1);
  }, []); // eslint-disable-line
  return (
    <div className="order-li">
      {phone}已抢订{randomNum}分钟前
    </div>
  );
}
